package com.wushi.lenovo.asia5b.app_ui.good.fragment;

import android.content.Context;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.mvp.base.BaseFragmentPagerAdapter;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.OrderFragmentView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.OrderFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.OrderItemEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_event.PostPackEvent;
import com.wushi.lenovo.asia5b.app_model.credit.bean.TopupInfoBean;
import com.wushi.lenovo.asia5b.app_model.good.orderitem.OrderItemType;
import com.wushi.lenovo.asia5b.app_model.other.CountModel;
import com.wushi.lenovo.asia5b.app_model.other.CountType;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static java.lang.System.out;
import static timber.log.Timber.d;

/**
 * Created by zhangyuncai on 2018/12/4.
 */
public class OrderFragment extends BaseMvpFragment<OrderFragmentView, OrderFragmentPresenter>
        implements OrderFragmentView {
    @BindView(R.id.vp_order)
    ViewPager mViewPager;
    @BindView(R.id.tablayout_order)
    TabLayout tabLayout;
    private List<Fragment> fragments;
    //当前选中
    private int currentPosition = 0;

    public void setCurrentPosition(int currentPosition) {
        this.currentPosition = currentPosition;
    }

    public static OrderFragment newInstance(Context context) {
        return (OrderFragment) Fragment.instantiate(context, OrderFragment.class.getName(), null);
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_order;
    }


    @Override
    protected void lazyFetchData() {
//        if (fragments == null || fragments.size() == 0) {
        if (true) {
            fragments = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                Bundle bundle = new Bundle();
                if (i == 0) {
                    bundle.putSerializable("type", OrderItemType.Verification);
                    fragments.add(OrderItemFragment.sNewStance(getContext(), OrderVeriFragment.class.getName(), bundle));
                } else if (i == 1) {
                    bundle.putSerializable("type", OrderItemType.Payment);
                    fragments.add(OrderItemFragment.sNewStance(getContext(), OrderItemFragment.class.getName(), bundle));
                } else if (i == 2) {
                    bundle.putSerializable("type", OrderItemType.Delivery);
                    fragments.add(OrderItemFragment.sNewStance(getContext(), OrderItemFragment.class.getName(), bundle));
                } else if (i == 3) {
                    bundle.putSerializable("type", OrderItemType.History);
                    fragments.add(OrderItemFragment.sNewStance(getContext(), OrderProblemFramgment.class.getName(), bundle));
                } else if (i == 4) {
                    bundle.putSerializable("type", OrderItemType.Problematic);
                    fragments.add(OrderItemFragment.sNewStance(getContext(), OrderProblemFramgment.class.getName(), bundle));
                }

            }
            mViewPager.setAdapter(new BaseFragmentPagerAdapter(getChildFragmentManager(), fragments, null));
            mViewPager.setOffscreenPageLimit(fragments.size());
            tabLayout.setScrollPosition(0, 0f, true);
            if (currentPosition >= 0 && currentPosition < fragments.size()) {
                setCurrentItem(currentPosition);
            }
        }
        initData();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
        initView();
        initEvent();
        resetView();
    }

    /**
     * 设置当前item
     *
     * @param position
     */
    public void setCurrentItem(int position) {
        if (position >= 0 && position < fragments.size() && mViewPager != null) {
            mViewPager.setCurrentItem(position);
        }
    }

    @Override
    protected void initView() {
        //Tablayout点击tab时去除黑色背景
        tabLayout.setTabRippleColor(ColorStateList.valueOf(getContext().getResources().getColor(R.color.white)));
        tabLayout.removeAllTabs();
        tabLayout.addTab(tabLayout.newTab().setCustomView(tabView(getString(R.string.order_verification))));
        tabLayout.addTab(tabLayout.newTab().setCustomView(tabView(getString(R.string.order_payment))));
        tabLayout.addTab(tabLayout.newTab().setCustomView(tabView(getString(R.string.order_delivery))));
        tabLayout.addTab(tabLayout.newTab().setCustomView(tabView(getString(R.string.order_history))));
        tabLayout.addTab(tabLayout.newTab().setCustomView(tabView(getString(R.string.order_problematic))));
    }

    private void resetView() {
        setTabCount(0, 0);
        setTabCount(1, 0);
        setTabCount(2, 0);
        setTabCount(3, 0);
        setTabCount(4, 0);
        if (mViewPager.getChildCount() > 0) {
            mViewPager.setCurrentItem(0);
        }
    }

    private View tabView(String tabName) {
        View view = View.inflate(getContext(), R.layout.item_order_tabview, null);
        TextView tv_order_tabtitle = view.findViewById(R.id.tv_order_tabtitle);
        TextView tv_order_tabcount = view.findViewById(R.id.tv_order_tabcount);
        tv_order_tabtitle.setText(tabName);
        tv_order_tabcount.setText("0");
        return view;
    }

    @Override
    protected void initData() {
        getPresenter().getOrdersCount();
    }

    @Override
    protected void initEvent() {
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                out.println("---<<<>>>---onTabSelected.position:" + tab.getPosition());
                mViewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                out.println("---<<<>>>---onTabReselected.position:" + tab.getPosition());
                mViewPager.setCurrentItem(tab.getPosition());
            }
        });
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setScrollPosition(position, 0f, true);
                currentPosition = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void getOrdersCountResult(ResultModel<CountModel> countModelResultModel, CountType type) {
        if (countModelResultModel.isSuccess() && countModelResultModel.getData() != null) {
            switch (type) {
                case Order_Verification: {
                    setTabCount(0, countModelResultModel.getData().getCount());
                }
                break;
                case Order_Payment: {
                    setTabCount(1, countModelResultModel.getData().getCount());
                }
                break;
                case Order_Delivery: {
                    setTabCount(2, countModelResultModel.getData().getCount());
                }
                break;
                case Order_History: {
                    setTabCount(3, countModelResultModel.getData().getCount());
                }
                break;
                case Order_Problematic: {
                    setTabCount(4, countModelResultModel.getData().getCount());
                }
                break;
                default:
                    break;
            }
        }
    }

    public void setTabCount(int index, int count) {
        try {
            if (index == 3) {//历史订单数量隐藏
                count = 0;
            }
            TextView tv_order_tabcount = tabLayout.getTabAt(index).getCustomView().findViewById(R.id.tv_order_tabcount);
            EyeUtils.setNumsByGone(tv_order_tabcount, count);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                d("--->>>>>>>>---登录成功");
//                    initData();
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                hasFetchData = false;
                resetView();
            }

        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderItemEvent(OrderItemEvent event) {
        if (event != null) {
            setCurrentItem(event.currentPosition);
        }
    }


    /**
     * 申请打包
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onPostPackEvent(PostPackEvent event) {
        setCurrentItem(1);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) //在ui线程执行
    public void onOrderPayEvent(OrderPayEvent event) {
        if (event != null && event.resultModel.isSuccess()) {
            if (event.topupInfoBean != null) {
                int orderPaymentType = event.topupInfoBean.OrderPaymentType;
                if (orderPaymentType == TopupInfoBean.OrderPaymentType_fist) {
                    //刷新处理中
                    if (event.topupInfoBean.goodsType == 0 || event.topupInfoBean.goodsType == 1) {//代购商品
                        setCurrentItem(0);
                    } else {//自营商品跳到发货中
                        setCurrentItem(2);
                    }
                } else if (orderPaymentType == TopupInfoBean.OrderPaymentType_second) {
                    //刷新代付款
                    setCurrentItem(1);
                } else if (orderPaymentType == TopupInfoBean.OrderPaymentType_diff) {
                    //刷新代付款
                    setCurrentItem(1);
                }
            }
        }


    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
